<?php

namespace App\Service\Pay\SysType;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Http\Middleware\OpenShop\MerchantAppAuth;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\OperateLogModel;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Cruise\Shop\CruiseShopService;

class PayAgainstService extends BasePaySysTypeService
{
    public function valid(): void
    {
        // 订单状态不对
        if ($this->orderModel->status != CruiseCheckAgainstModel::STATUS_WAIT) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "违约函状态错误");
        }
    }

    public function priceLists(): array
    {
        return collect([
            [
                'name'  => '违约金额',
                'price' => $this->orderModel->price,
            ],
        ])->filter(function ($item) {
            if ($item['price'] == 0) {
                return false;
            }

            return true;
        })->values()->toArray();
    }

    public function paySuccessCheck(): bool
    {
        // 主订单已支付完成、直接返回成功 - 幂等
        if ($this->orderModel->status == CruiseCheckAgainstModel::STATUS_OK) {
            return true;
        }

        return false;
    }

    public function paySuccessSaveOrder(int $amount): void
    {
        MerchantAppAuth::$userId = $this->userId;
        $this->orderModel = $this->orderModel->onePaySuccess($amount);
    }

    // 支付成功要干的事
    public function paySuccessAfter(): void
    {
        // 完全支付
        if ($this->orderModel->status == CruiseCheckAgainstModel::STATUS_OK) {

            // 门店状态 == 稽核关闭，就打开它
            $cashRegisterStatus =  (new RmsShopApi())->getShopByIds([$this->orderModel->shopId])['data']['shopList'][0]['cashRegisterStatus'] ?? RmsShopRemote::SHOP_CASH_REGISTER_STATUS_OK;
            if ($cashRegisterStatus == RmsShopRemote::SHOP_CASH_REGISTER_STATUS_CHECK_OFF) {
//                CruiseShopService::updateCashRegisterStatusByShopId($this->orderModel->shopId, RmsShopRemote::SHOP_CASH_REGISTER_STATUS_OK);
                RmsShopRemote::updateShopFieldById($this->orderModel->shopId, ['cashRegisterStatus' => RmsShopRemote::SHOP_CASH_REGISTER_STATUS_OK]);
            }

            // 操作日志
            OperateLogModel::add(
                OperateLogModel::BUSINESS_AGAINST_DETAIL,
                $this->orderModel->businessId,
                $this->orderModel->id,
                '商家已处理',
                '支付成功',
                OperateLogModel::STATUS_OK,
                $this->userId
            );
            return;
        }
    }
}
